#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2018/1/12 0012 15:12
# @Author  : Arliki
# @email   : hkdnxycz@outlook.com
# @File    : collage.py
import pymysql, time, os, random


# →→→→!!{添加至订单列表}!!←←←←
def go_order(id=0):
    cur1 = con.cursor()
    cur2 = con.cursor()
    if id == 0:
        num = cur1.execute("select users_id,max,goods_id,id from ecs_collage_list where status=3")
        # 已完成拼单
        if num > 0:
            for row in cur1.fetchall():
                users = row[0].split(',')
                free = random.randint(1, len(users) - 1)
                max = row[1]
                goods_id = row[2]
                collage_id = row[3]
                if max == len(users):
                    try:
                        cur2.execute("select gys_id from ecs_goods where goods_id='%s'" % goods_id)
                        for g in cur2.fetchall():
                            gys_id = g[0]
                    except:
                        gys_id = 0
                    do_insert(users, collage_id, goods_id, gys_id, free)
    else:
        cur1.execute("select users_id,max,goods_id,id from ecs_collage_list where id=%s" % id)
        for row in cur1.fetchall():
            users = row[0].split(',')
            free = random.randint(1, len(users) - 1)
            max = row[1]
            goods_id = row[2]
            collage_id = row[3]
            if max == len(users):
                try:
                    cur2.execute("select gys_id from ecs_goods where goods_id='%s'" % goods_id)
                    for g in cur2.fetchall():
                        gys_id = g[0]
                except:
                    gys_id = 0
                do_insert(users, collage_id, goods_id, gys_id, free)
    cur1.close()
    cur2.close()
    return num


def do_insert(users, collage_id, goods_id, gys_id, free):
    for user_id in users:
        if user_id == users[free]:
            curs = con.cursor()
            sql = "insert into ecs_wxrefun (user_id, price, order_sn, add_time,act_id) (select user_id,money,order_sn,add_time from ecs_collage_pay,-1 where user_id='%s')" % user_id
            curs.execute(sql)
            curs.close()
            is_free = True
        # 插入订单表
        if is_free:
            sql1 = "insert into ecs_order_info (user_id, order_sn,goods_amount, money_paid,add_time, confirm_time, pay_time,consignee, country, province, city, district, address, mobile, order_status, shipping_status, pay_status, pay_id, pay_name, how_oos, referer,agency_id ) (select '%s',order_sn,0,0,add_time,add_time,add_time,consignee,country,province,city,district,address,mobile,'1','0','2','1','微信支付','等待所有商品备齐后再发','拼单购买','%s' from ecs_collage_pay as c left join ecs_user_address as u on c.user_id=u.user_id where c.user_id='%s' and collage_id='%s' order by c.id desc limit 1)" % (
                user_id, gys_id, user_id, collage_id)
            price = [0]
        else:
            # 消费金额
            cur2.execute(
                "select money from ecs_collage_pay where user_id='%s' and collage_id='%s'order by Id desc limit 1" % (
                    user_id, collage_id))
            price = cur2.fetchone()
            cur2.close()
            sql1 = "insert into ecs_order_info (user_id, order_sn,goods_amount, money_paid,add_time, confirm_time, pay_time,consignee, country, province, city, district, address, mobile, order_status, shipping_status, pay_status, pay_id, pay_name, how_oos, referer,agency_id ) (select '%s',order_sn,money,money,add_time,add_time,add_time,consignee,country,province,city,district,address,mobile,'1','0','2','1','微信支付','等待所有商品备齐后再发','拼单购买','%s' from ecs_collage_pay as c left join ecs_user_address as u on c.user_id=u.user_id where c.user_id='%s' and collage_id='%s' order by c.id desc limit 1)" % (
        user_id, gys_id, user_id, collage_id)
        cur2 = con.cursor()
        cur2.execute(sql1)
        con.commit()
        # 插入订单商品表
        cur3 = con.cursor()
        cur3.execute(
            "select order_id from ecs_order_info where user_id='%s' and referer='拼单购买' order by order_id desc limit 1" % user_id)
        order_id = cur3.fetchone()
        sql2 = "insert into ecs_order_goods (order_id, goods_id, goods_name, goods_sn, goods_number, market_price, goods_price, goods_attr,is_real, goods_attr_id) (select '%s','%s',goods_name,goods_sn,'1','%s','%s','拼单购买','1',IFNULL(goods_attr_id,0) from ecs_goods as g left join ecs_goods_attr as a on g.goods_id=a.goods_id where g.goods_id='%s')" % (
        order_id[0], goods_id, price[0], price[0], goods_id)
        cur3.execute(sql2)
        cur3.close()
        con.commit()
        time.sleep(1)
    cur1 = con.cursor()
    cur1.execute("update ecs_collage_list set status=1 where id='%s'" % collage_id)
    cur1.execute("delete from ecs_collage_index where collage_id='%s'" % collage_id)
    with open('./logs/collage_ok.log', 'a+', encoding='utf-8') as f:
        f.write("%s :%s collage_id:%s" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), str(users), collage_id))
    cur1.close()


# →→→→!!{未完成添加至退款列表}!!←←←←
def go_wxrefun():
    cur1 = con.cursor()
    num = cur1.execute(
        "select users_id,max,Id,goods_id from ecs_collage_list where end_time<'%s' and status=0" % now_time)
    if num > 0:
        for row in cur1.fetchall():
            users = row[0].split(',')
            max = row[1]
            id = row[2]
            goods_id = row[3]
            cur2 = con.cursor()
            if max == len(users):
                do_insert(users, id, goods_id)
            else:
                for user_id in users:
                    cur2.execute(
                        "insert into ecs_wxrefun (user_id, price, order_sn, add_time) (select user_id,money,order_sn,add_time from ecs_collage_pay where user_id='%s')" % user_id)
                    con.commit()
                cur2.execute("update ecs_collage_list set status=2 where id=%s" % id)
                cur2.execute("delete from ecs_collage_index where collage_id=%s" % id)
                with open('./logs/collage_wxrefun.log', 'a+', encoding='utf-8') as f:
                    f.write(
                        "%s :%s collage_id:%s" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), str(users), id))
    cur1.close()
    return num


# →→→→!!{更新执行时间}!!←←←←
def get_time():
    cur1 = con.cursor()
    num = cur1.execute("select end_time from ecs_collage_list where status=0")
    upd_time = 10 * 60
    if num > 0:
        for row in cur1.fetchall():
            upd_time = min(abs(int(row[0]) - int(time.time() + 30)), upd_time)
    cur1.close()
    return upd_time


def to_test():
    cur = con.cursor()
    cur.execute(
        "insert into ecs_wxrefun (user_id,price,order_sn,add_time) (select user_id,money,order_sn,add_time from ecs_collage_pay where id >15)")
    cur.close()

if __name__ == '__main__':
    while True:
        con = pymysql.connect(host='', user='arliki', passwd='', db='youxian', charset='utf8')
        try:
            now_time = int(time.time())
            num1 = go_order()
            if num1 > 0:
                print("Processing completed", num1, " is into order.")
            num = go_wxrefun()
            if num > 0:
                go_wxrefun()
                os.system("python wxpub.py")
                print("Processing completed", num, " is refun.")
            if 0:
                # to_test()
                os.system("python wxpub.py")
                print("Processing completed", num, " is refun.")
            upd_time = get_time()
            con.close()
            print('wait for', upd_time, 'seconds')
            with open("./logs/working_log.log", 'a+', encoding='utf-8') as f:
                f.write('%s wait for %s seconds' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), upd_time))
            time.sleep(upd_time)
        except Exception:
            with open("./logs/error_log.log", 'a+', encoding='utf-8') as f:
                f.write(Exception)
